<template>
  <div class="m-graph-relation" :style="style">
    <div class="u-graph" ref="graphRef"></div>
    <Toolbar
      @changeFullScreen="changeFullScreen"
      class="u-toolbar"
      v-if="showToolbar"
    ></Toolbar>
  </div>
</template>

<script setup name="MGraphRelation">
import { onMounted, ref, inject, useAttrs } from 'vue'
import Toolbar from './toolbar.vue'
import graphInit from '../../../shared/graph-relation/graphInit'
import useResize from '../../../utils/resize'

const props = defineProps({
  data: Object,
  limitLen: {
    type: Number,
    default: 6,
  },
  nodeVGap: {
    type: Number,
    default: 30,
  },
  nodeHGap: {
    type: Number,
    default: 30,
  },
  nodeWidth: {
    type: Number,
    default: 200,
  },
  defaultZoom: {
    type: Number,
    default: 0.7,
  },
  minZoom: {
    type: Number,
    default: 0.3,
  },
  maxZoom: {
    type: Number,
    default: 2,
  },
  mouseZoomable: {
    type: Boolean,
    default: true,
  },
  showToolbar: Boolean,
})
const emit = defineEmits(['clickLink', 'clickNode', 'clickToolbar'])

const attrs = useAttrs()

const graphRef = ref()
let graph = null
let graphOriginWidth = null
let graphOriginHeight = null
const style = ref(attrs.style)

function render() {
  graph = graphInit({
    graphRef,
    data: props.data,
    defaultZoom: props.defaultZoom,
    minZoom: props.minZoom,
    maxZoom: props.maxZoom,
    mouseZoomable: props.mouseZoomable,
    limitLen: props.limitLen,
    nodeVGap: props.nodeVGap,
    nodeHGap: props.nodeHGap,
    nodeWidth: props.nodeWidth,
    clickLink(e, model) {
      emit('clickLink', model)
    },
    clickNode(e, model) {
      emit('clickNode', model)
    },
  })
}

function changeFullScreen(d) {
  if (d === 'fullScreen') {
    style.value = {
      position: 'fixed',
      left: 0,
      top: 0,
      zIndex: 1000,
      width: '100vw',
      height: '100vh',
    }
    graph.changeSize(window.innerWidth, window.innerHeight)
    graph.myInit()

    emit('clickToolbar', 'fullScreen')
  } else {
    style.value = attrs.style
    graph.changeSize(graphOriginWidth, graphOriginHeight)
    graph.myInit()

    emit('clickToolbar', 'normalScreen')
  }
}

onMounted(() => {
  graphOriginWidth = graphRef.value.clientWidth
  graphOriginHeight = graphRef.value.clientHeight
  render()
})

useResize(() => graph.myResize())

defineExpose({
  getGraphInstance() {
    return graph
  },
})
</script>

<script>
export default {
  inheritAttrs: false,
}
</script>

<style lang="stylus" scoped>
.m-graph-relation
  position relative
  .u-graph
    width 100%
    height 100%
    background #F3F5F7
  .u-toolbar
    position absolute
    right 16px
    bottom 19px
</style>
